package com.xinnet.mms.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.mms.allot.dao.CustomAllotDao;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.customtransfer.service.CustomSystematizationService;
import com.xinnet.mms.customtransfer.service.IntentionCustomTransferService;
import com.xinnet.mms.customtransfer.service.MakeOfServiceCustomService;
import com.xinnet.mms.customtransfer.service.NewRegisterCustomTransferService;
import com.xinnet.mms.customtransfer.service.OfServiceCustomTransferService;
import com.xinnet.mms.customtransfer.service.RetrieveCustomTransferService;
import com.xinnet.mms.customtransfer.service.SecondDevelopCustomTransferService;
import com.xinnet.mms.dept.service.DeptService;
import com.xinnet.mms.emp.service.HyMangerEmpDataHandleService;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.Emp;
import com.xinnet.mms.entity.ScanningList;
import com.xinnet.mms.enums.CustomerTypeEnmu;
import com.xinnet.mms.enums.ProductTypeEnum;
import com.xinnet.mms.member.service.MemberService;
import com.xinnet.mms.quartz.job.CustomAllotJob;
import com.xinnet.mms.quartz.job.JobTimeService;
import com.xinnet.mms.utils.CustomerManage;

@Controller
@RequestMapping(value = "/authority/synJob")
public class SynJobController {
	@Autowired
	private CustomSystematizationService customSystematizationService; 
	@Autowired
	private NewRegisterCustomTransferService newRegisterCustomTransferService;
	@Autowired
	private IntentionCustomTransferService intentionCustomTransferService;
	@Autowired
	private OfServiceCustomTransferService ofServiceCustomTransferService;
	@Autowired
	private SecondDevelopCustomTransferService secondDevelopCustomTransferService;
	@Autowired
	private RetrieveCustomTransferService retrieveCustomTransferService;
	@Autowired
	private MakeOfServiceCustomService makeOfServiceCustomService;
	@Autowired
	private HyMangerEmpDataHandleService hyMangerEmpDataHandle;
	@Autowired
	private MemberService memberService;
	@Autowired
	private CustomAllotService customAllotService;
	@Autowired
	private JobTimeService jobTimeService;
	/**客户分配*/
	@Autowired
	private CustomAllotDao customAllotDao;
	@Autowired
	private DeptService deptService;
	
	private static String trustServerAddr = ConfigUtil.getString("trustIp.server");
	
	private static Log log = LogFactory.getLog(SynJobController.class);
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping(value = "/synJobPage")
	public String synJobPage(HttpServletRequest request,HttpServletResponse response, Model model){
		Emp currentUser = (Emp) request.getSession().getAttribute("currentUser");
		if (null == currentUser) {
			return "redirect:/login/loginPage";
		}
		// 客户管理查询条件：所属人的部门组织Ztree Json
		String deptJson = AppGlobalContainer.deptIdToDeptJsonMap.get(currentUser.getId());
		if(deptJson==null){
			deptJson = "["
					+ deptService.getDeptTreeByDeptId(currentUser.getId()) + "]";
			AppGlobalContainer.deptIdToDeptJsonMap.put(currentUser.getId(), deptJson);
		}
		model.addAttribute("deptJson", deptJson);
		CustomerTypeEnmu[] customerTypeEnmuArray = CustomerTypeEnmu.values();
		request.setAttribute("customerTypeEnmuArray", customerTypeEnmuArray);
		
		ProductTypeEnum[] productTypeEnumArray = ProductTypeEnum.values();
		model.addAttribute("productTypeEnumArray", productTypeEnumArray);
		return "/authority/synJobPage";
	}
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@RequestMapping(value = "/addAllotCustomer")
	public void addAllotCustomer(Customer customer, HttpServletRequest request,HttpServletResponse response, Model model){
		
		try {
			Customer member = memberService.getMemberByCusId(customer.getCustomId());
			member.setCustomerSource("网站");
			member.setCustomState(CustomerManage.ACCEPT_YES);
			member.setPusherId("system");
			member.setEmpno(customer.getEmpId());
			member.setProductLabel("D");
			member.setCustomerType(customer.getCustomType());
			customAllotService.allot(member, customer.getCustomType());
			response.getWriter().print("1");
		} catch (Exception e) {
			try {
				response.getWriter().print("添加失败！");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@ResponseBody
	@RequestMapping(value = "/customTransfer")
	public String customTransfer(HttpServletRequest request,HttpServletResponse response){
		try {
			customSystematizationService.getBaseData();
			// 新注册客户流转
			newRegisterCustomTransferService.newRegisterCustomTransfer();
			// 意向客户流转
			intentionCustomTransferService.intentionCustomTransfer();
			// 服务期客户流转
			ofServiceCustomTransferService.ofServiceCustomTransfer();
			// 二次开发客户流转
			secondDevelopCustomTransferService.secondDevelopCustomTransfer();
			// 回收客户流转
			retrieveCustomTransferService.retrieveCustomTransfer();
			// 生成服务期客户
			makeOfServiceCustomService.makeOfServiceCustomer();
		} catch (Exception e) {
			return "false";
		}
		return "true";
	}
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@ResponseBody
	@RequestMapping(value = "/customAllot")
	public String customAllot(HttpServletRequest request,HttpServletResponse response){
		try {
			log.info("<超时扫描开始>");
			List<ScanningList> list = customAllotService.getAllScanningList();
			// 时间列表中有客户数据时进行处理
			if (list == null || list.isEmpty()) {
				log.info("<当前没有客户需要超时分配>");
				return "true";
			}
			log.info("<扫描业务员接收客户状态" + "当前待接收客户个数:(" + list.size() + ")>");
			int count = 0;
			for (ScanningList scann : list) {
				count++;
				log.info("超时扫描处理第【" + count + "】条开始");
				customAllotService.handleScaningList(scann);
				log.info("超时扫描处理第【" + count + "】条结束");
			}
		} catch (Exception e) {
			// TODO: handle exception
			return "false";
		}
		return "true";
	}
	
	/*@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@ResponseBody
	@RequestMapping(value = "/lostCustomAllot")
	public String lostCustomAllot(HttpServletRequest request,HttpServletResponse response){
		try {
			customAllotService.lostCustomAllot();
		} catch (Exception e) {
			// TODO: handle exception
			return "false";
		}
		return "true";
	}*/
	
	
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@ResponseBody
	@RequestMapping(value = "/synEmp")
	public String synEmp(HttpServletRequest request,HttpServletResponse response){
		try {
			hyMangerEmpDataHandle.empSynchronous();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "false";
		}
		return "true";
	}
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@ResponseBody
	@RequestMapping(value = "/synCustomer")
	public String synCustomer(HttpServletRequest request,HttpServletResponse response){
		try {
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// 获取取得客户区间数
			int limit = Integer.parseInt(ConfigUtil.getString("LIMIT"));
			// 获取导入客户类型(全部/当前)
			int timeSet = Integer.parseInt(ConfigUtil.getString("GETTYPE"));

			if (timeSet == CustomerManage.TIMESET_ALL) {
				log.info("<导入全部会员开始>");
				// 获取会员总记录数
				int count = memberService.getAllMemberCount();
				for (int top = 0; top <= count; top += limit) {
					List<Customer> list = memberService.getMemberByLimit(top, limit);
					if (list == null) {
						log.info("<当前需要导入的老客户数为0>");
						return "true";
					} else {
						// 对获取的会员进行分配
						for (Customer customer : list) {
							customer.setCustomerSource("网站");
							customer.setCustomState(CustomerManage.ACCEPT_NO);
							customer.setPusherId("system");
							customer.setIsAllot(0);
							customer.setIsReDevel(0);
							customer.setAddTime(sf.format(new Date()));
							customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
							// 如果区域为空 则默认设置为北京
							String areaName = customer.getAreaName();
							if (areaName == null || "".equals(areaName)) {
								customer.setRegionalId(CustomerManage.BEIJING);
								customer.setAreaName("北京市");
							}
							try {
								customAllotService.allot(customer,CustomerManage.NEW_CUSTOMER);
							} catch (Exception e) {
								log.error("<同步会员出错-会员ID:" + customer.getCusId()
										+ "," + e.getMessage() + ">", e);
							}
							log.info("<---TIME:" + customer.getAddTime()
									+ "---扫描新注册客户---ID：" + customer.getCusId()
									+ " UserName：" + customer.getCname() + ">");
						}
					}
				}
				log.info("<导入全部会员END>");
			} else {
				log.info("<导入区间会员开始>");
				// 获取时间戳 如果时间戳为空则添加一条当前时间的时间戳
				Customer jobTimeCustomer = new Customer();
				jobTimeCustomer = jobTimeService.getJobTime(CustomerManage.SYSNMEMBER);
				if (jobTimeCustomer == null) {
					jobTimeCustomer = new Customer();
					String time = sf.format(new Date());
					jobTimeCustomer.setTimeStamp(time);
					jobTimeCustomer.setJobId(UUID.randomUUID().toString());
					jobTimeCustomer.setJobType(CustomerManage.SYSNMEMBER);
					jobTimeService.addJobTime(jobTimeCustomer);
				}
				// 获取设置的时间区间的所有新注册会员
				List<Customer> customerList = memberService
						.getMemberByTimeSet(jobTimeCustomer.getTimeStamp());
				if (customerList == null || customerList.isEmpty()) {
					log.info("<没有新注册客户>");
					return "true";
				}
				int count = 0;
				// 对获取的会员进行分配
				for (Customer customer : customerList) {
					log.info("<---TIME:" + customer.getAddTime()
							+ "---扫描新注册客户---ID：" + customer.getCusId()
							+ " UserName：" + customer.getCname() + " 当前第 【" + count
							+ "】 条|处理开始>");
					customer.setCustomerSource("网站");
					customer.setCustomState(CustomerManage.ACCEPT_NO);
					customer.setPusherId("system");
					customer.setIsAllot(0);
					customer.setIsReDevel(0);
					customer.setCustomerType(CustomerManage.NEW_CUSTOMER);
					jobTimeCustomer.setTimeStamp(customer.getAddTime());
					// 如果区域为空 则默认设置为北京
					String areaName = customer.getAreaName();
					if (areaName == null || "".equals(areaName)) {
						customer.setRegionalId(CustomerManage.BEIJING);
						customer.setAreaName("北京市");
					}
					try {
						customAllotService.allot(customer,CustomerManage.NEW_CUSTOMER);
					} catch (Exception e) {
						jobTimeService.updateJobTime(jobTimeCustomer);
						log.error("<同步区间会员出错-会员ID:" + customer.getCusId() + ","+ e.getMessage() + " 任务停止>", e);
						return "false";
					}
					count++;
					log.info("<---TIME:" + customer.getAddTime()+ "---扫描新注册客户---ID：" + customer.getCusId()+ " UserName：" + customer.getCname() + " 当前第 【" + count+ "】 条|处理完毕>");
				}
				jobTimeService.updateJobTime(jobTimeCustomer);
				log.info("<导入区间会员END>");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			return "false";
		}
		return "true";
	}
	/**
	 * 
	 *
	 * 功能描述：同步ip认证列表
	 * 
	 * @author 湛智
	 *
	 * @throws 2014年8月25日
	 *
	 */
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@ResponseBody
	@RequestMapping(value = "/sysnIp")
	public String sysnTrustIpData(HttpServletRequest request,HttpServletResponse response){
		CustomAllotJob.setIpString(CustomAllotJob.getTrustIpData(trustServerAddr, ""));
		return "true";
	}
	
}
